import calendar
import datetime
import json
import random
import time

from django.db import transaction
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone

from admins.models import TUser
from booksRecord.models import TRecord
from cloudLibraryDjango import common
from newbooksrecd.models import TBook


def getList(request):
    userName = request.session.get("user_name")
    return render(request, 'newBooksRecd/list.html', locals())


def list(request):
    # 表格要展现的数据
    newBooks = TBook.objects.filter(book_status="0")
    # 处理成LayUi官方文档的格式
    lis = commonList(newBooks)

    # 调用分页方法
    res = common.getPageData(request, newBooks, lis)
    result = common.getResult(newBooks.count(), res)
    return HttpResponse(json.dumps(result))


def searchList(request):
    # 表格要展现的数据
    newBooks = TBook.objects.filter(book_status="0")

    bookName = request.GET.get("bookName")
    if bookName:
        newBooks = newBooks.filter(book_name=bookName)

    bookIsbn = request.GET.get("bookIsbn")
    if bookIsbn:
        newBooks = newBooks.filter(book_isbn=bookIsbn)

    res = commonList(newBooks)

    # 放在一个列表里
    result = common.getResult(newBooks.count(), res)
    return JsonResponse(result)


def show_edit(request, bookIds):
    if bookIds:
        ids = bookIds
    users = TUser.objects.filter(user_status='0')

    return render(request, 'newBooksRecd/edit.html', locals())


# 借阅
@transaction.atomic
def edit(request):
    savePoint = None
    status = False

    if request.POST:
        bookIds = json.loads(request.POST['bookIds'])
        books = TBook.objects.filter(book_id__in=bookIds)

        userId = request.POST.get("userId")

        user = TUser.objects.filter(user_id=userId).first()

        time3 = timezone.now()
        time2 = datetime.timedelta(days=30)
        try:
            # 批量插入
            record_list = []
            for book in books:
                num = random.randint(100000, 999999)
                ts = calendar.timegm(time.gmtime())
                recordId = str(num) + "_" + str(ts)

                # 首先生成对象
                tRecord = TRecord(record_id=recordId, record_bookname=book.book_name, record_bookisbn=book.book_isbn,
                                  record_borrower=user, record_borrowtime=time3.strftime("%Y-%m-%d"))

                record_list.append(tRecord)

            savePoint = transaction.savepoint()  # 事务保存点
            # 借助orm批量插入
            print("批量更新前", status)
            ss = TRecord.objects.bulk_create(record_list)
            if ss:
                status = True

            ii = books.update(book_borrowtime=time3.strftime("%Y-%m-%d"),
                         book_returntime=(time3 + time2).strftime("%Y-%m-%d"), book_borrower=user, book_status="1")

            if ii > 0:
                status = True

        except Exception as error:
            if savePoint:
                # 事务回滚
                transaction.rollback(savePoint)
            status = error.__str__()
            print(status)

        if status is True:
            result = {"code": 0, "msg": "借阅成功"}
            return JsonResponse(result, safe=False)

    result = {"code": 1, "msg": "借阅失败"}
    return JsonResponse(result)


# 查询的公共方法
def commonList(newBooks):
    res = []
    for newBook in newBooks:
        data = dict()
        data['bookId'] = newBook.book_id
        data['bookName'] = newBook.book_name
        data['bookIsbn'] = newBook.book_isbn
        data['price'] = newBook.book_price
        data['author'] = newBook.book_author
        data['publish'] = newBook.book_press
        data['bookPages'] = newBook.book_pagination
        data['publishDate'] = newBook.book_uploadtime
        res.append(data)
    return res
